using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace SmartMedical.WinUI
{
    /// <summary>
    /// 开中药窗体
    /// 用于录入中药处方信息，包括药品管理和处方保存
    /// </summary>
    public partial class PrescribeChineseMedicineForm : Form
    {
        #region 私有字段
        /// <summary>
        /// HTTP客户端，用于调用后端API
        /// </summary>
        private readonly HttpClient _httpClient;

        /// <summary>
        /// API基础URL - 写入API端口
        /// </summary>
        private const string _apiBaseUrl = "http://localhost:5165";

        /// <summary>
        /// 患者ID
        /// </summary>
        private readonly long _patientId;

        /// <summary>
        /// 患者姓名
        /// </summary>
        private readonly string _patientName;

        /// <summary>
        /// 中药列表
        /// </summary>
        private readonly List<ChineseMedicineItem> _medicines;
        #endregion

        #region 构造函数
        /// <summary>
        /// 初始化开中药窗体
        /// </summary>
        public PrescribeChineseMedicineForm()
        {
            InitializeComponent();

            // 初始化HTTP客户端
            _httpClient = new HttpClient();
            _httpClient.Timeout = TimeSpan.FromSeconds(30);

            // 初始化药品列表
            _medicines = new List<ChineseMedicineItem>();

            // 初始化窗体
            InitializeForm();
        }

        /// <summary>
        /// 初始化开中药窗体（带患者信息）
        /// </summary>
        /// <param name="patientId">患者ID</param>
        /// <param name="patientName">患者姓名</param>
        public PrescribeChineseMedicineForm(long patientId, string patientName) : this()
        {
            _patientId = patientId;
            _patientName = patientName;

            // 显示患者信息
            lblPatientIdValue.Text = patientId.ToString();
            lblPatientNameValue.Text = patientName;
        }
        #endregion

        #region 初始化方法
        /// <summary>
        /// 初始化窗体设置
        /// </summary>
        private void InitializeForm()
        {
            this.Text = "开中药";

            // 初始化下拉框数据
            InitializeComboBoxes();

            // 设置DataGridView
            SetupDataGridView();

            // 刷新药品列表
            RefreshMedicineList();
        }

        /// <summary>
        /// 初始化下拉框数据
        /// </summary>
        private void InitializeComboBoxes()
        {
            // 初始化用药频次下拉框
            cmbFrequency.Items.AddRange(new string[]
            {
                "每日一次",
                "每日两次",
                "每日三次",
                "每8小时一次",
                "每12小时一次",
                "睡前一次",
                "必要时服用"
            });

            // 初始化用法下拉框
            cmbUsage.Items.AddRange(new string[]
            {
                "水煎服",
                "开水冲服",
                "温开水送服",
                "饭前服用",
                "饭后服用",
                "空腹服用",
                "睡前服用",
                "外敷",
                "泡茶饮用"
            });

            // 设置默认选中项
            if (cmbFrequency.Items.Count > 0)
                cmbFrequency.SelectedIndex = 0;
            if (cmbUsage.Items.Count > 0)
                cmbUsage.SelectedIndex = 0;
        }

        /// <summary>
        /// 设置DataGridView样式
        /// </summary>
        private void SetupDataGridView()
        {
            dgvMedicines.AutoGenerateColumns = false;
            dgvMedicines.AllowUserToAddRows = false;
            dgvMedicines.AllowUserToDeleteRows = false;
            dgvMedicines.ReadOnly = true;
            dgvMedicines.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvMedicines.MultiSelect = false;
            dgvMedicines.BackgroundColor = Color.White;
            dgvMedicines.BorderStyle = BorderStyle.Fixed3D;
        }
        #endregion

        #region 事件处理方法
        /// <summary>
        /// 添加药品按钮点击事件
        /// </summary>
        private void BtnAddMedicine_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证输入
                if (!ValidateMedicineInput())
                    return;

                // 创建药品项
                var medicine = new ChineseMedicineItem
                {
                    MedicineName = txtMedicineName.Text.Trim(),
                    Specification = txtSpecification.Text.Trim(),
                    Dosage = txtDosage.Text.Trim(),
                    Frequency = cmbFrequency.Text,
                    Duration = txtDuration.Text.Trim(),
                    Usage = cmbUsage.Text,
                    Remark = txtRemark.Text.Trim()
                };

                // 添加到列表
                _medicines.Add(medicine);

                // 刷新显示
                RefreshMedicineList();

                // 清空输入
                ClearMedicineInput();

                MessageBox.Show("药品添加成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加药品时发生错误：{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 删除药品按钮点击事件
        /// </summary>
        private void BtnRemoveMedicine_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgvMedicines.SelectedRows.Count == 0)
                {
                    MessageBox.Show("请选择要删除的药品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                var selectedIndex = dgvMedicines.SelectedRows[0].Index;
                if (selectedIndex >= 0 && selectedIndex < _medicines.Count)
                {
                    var medicineName = _medicines[selectedIndex].MedicineName;

                    var result = MessageBox.Show($"确定要删除药品 '{medicineName}' 吗？", "确认删除",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    if (result == DialogResult.Yes)
                    {
                        _medicines.RemoveAt(selectedIndex);
                        RefreshMedicineList();
                        MessageBox.Show("药品删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除药品时发生错误：{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 保存按钮点击事件
        /// </summary>
        private async void BtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证处方信息
                if (!ValidatePrescriptionInfo())
                    return;

                // 保存处方
                var success = await SaveChineseMedicinePrescriptionAsync();
                if (success)
                {
                    MessageBox.Show("中药处方保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存处方时发生错误：{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
        #endregion

        #region 验证方法
        /// <summary>
        /// 验证药品输入
        /// </summary>
        /// <returns>验证结果</returns>
        private bool ValidateMedicineInput()
        {
            if (string.IsNullOrWhiteSpace(txtMedicineName.Text))
            {
                MessageBox.Show("请输入药品名称", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtMedicineName.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtDosage.Text))
            {
                MessageBox.Show("请输入剂量", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtDosage.Focus();
                return false;
            }

            if (cmbUsage.SelectedIndex == -1)
            {
                MessageBox.Show("请选择用法", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cmbUsage.Focus();
                return false;
            }

            return true;
        }

        /// <summary>
        /// 验证处方信息
        /// </summary>
        /// <returns>验证结果</returns>
        private bool ValidatePrescriptionInfo()
        {
            if (string.IsNullOrWhiteSpace(txtDiagnosis.Text))
            {
                MessageBox.Show("请输入诊断信息", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtDiagnosis.Focus();
                return false;
            }

            if (_medicines.Count == 0)
            {
                MessageBox.Show("请至少添加一种药品", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            return true;
        }
        #endregion

        #region 辅助方法
        /// <summary>
        /// 刷新药品列表显示
        /// </summary>
        private void RefreshMedicineList()
        {
            dgvMedicines.DataSource = null;
            dgvMedicines.DataSource = _medicines;
            dgvMedicines.Refresh();
        }

        /// <summary>
        /// 清空药品输入
        /// </summary>
        private void ClearMedicineInput()
        {
            txtMedicineName.Clear();
            txtSpecification.Clear();
            txtDosage.Clear();
            txtDuration.Clear();
            txtRemark.Clear();

            if (cmbUsage.Items.Count > 0)
                cmbUsage.SelectedIndex = 0;
            if (cmbFrequency.Items.Count > 0)
                cmbFrequency.SelectedIndex = 0;

            txtMedicineName.Focus();
        }

        /// <summary>
        /// 保存中药处方到服务器
        /// </summary>
        /// <returns>保存结果</returns>
        private async Task<bool> SaveChineseMedicinePrescriptionAsync()
        {
            try
            {
                // 创建处方数据，匹配后端API的数据结构
                var prescriptionData = new
                {
                    PatientId = _patientId,
                    PatientName = _patientName,
                    Diagnosis = txtDiagnosis.Text.Trim(),
                    Remark = txtPrescriptionRemark.Text.Trim(),
                    Medicines = _medicines,
                    Doctor = Properties.Settings.Default.DisplayName ?? "当前医生" // 从登录信息获取医生姓名
                };

                // 序列化数据
                var jsonContent = JsonConvert.SerializeObject(prescriptionData);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                // 调用API
                var response = await _httpClient.PostAsync($"{_apiBaseUrl}/api/Medical/CreateChineseMedicinePrescription", content);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<SavePrescriptionResult>(responseContent);

                    if (result != null && result.Code == 200)
                    {
                        return true;
                    }
                    else
                    {
                        MessageBox.Show(result?.Msg ?? "保存失败", "错误",
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                }
                else
                {
                    MessageBox.Show($"服务器响应错误：{response.StatusCode}", "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }
            catch (HttpRequestException)
            {
                MessageBox.Show("网络连接失败，请检查网络设置", "网络错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            catch (TaskCanceledException)
            {
                MessageBox.Show("请求超时，请重试", "超时错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存处方时发生错误：{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        #endregion

        #region 资源释放
        /// <summary>
        /// 释放HttpClient资源
        /// </summary>
        private void DisposeHttpClient()
        {
            _httpClient?.Dispose();
        }
        #endregion

        private void panelButtons_Paint(object sender, PaintEventArgs e)
        {

        }
    }

    #region 数据模型类
    /// <summary>
    /// 中药项数据模型
    /// </summary>
    public class ChineseMedicineItem
    {
        /// <summary>
        /// 药品名称
        /// </summary>
        public string MedicineName { get; set; } = string.Empty;
        
        /// <summary>
        /// 规格
        /// </summary>
        public string Specification { get; set; } = string.Empty;
        
        /// <summary>
        /// 剂量
        /// </summary>
        public string Dosage { get; set; } = string.Empty;
        
        /// <summary>
        /// 频次
        /// </summary>
        public string Frequency { get; set; } = string.Empty;
        
        /// <summary>
        /// 疗程
        /// </summary>
        public string Duration { get; set; } = string.Empty;
        
        /// <summary>
        /// 用法
        /// </summary>
        public string Usage { get; set; } = string.Empty;
        
        /// <summary>
        /// 备注
        /// </summary>
        public string Remark { get; set; } = string.Empty;
    }
    
    // 注意：处方数据直接使用匿名对象发送到后端API，无需单独的数据模型类
    
    // SavePrescriptionResult类已在PrescribeWesternMedicineForm.cs中定义，此处不重复定义
    #endregion
}